package org.changchen.fgt.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**   
* @ClassName:  LiveTestUtil   
* @Description:CSV工具类   
* @author:     ChangChen 
* @date:       2024-03-29 13:56
* @Copyright:  2024 ChangChen. All rights reserved. 
*/
@Slf4j
public class CSVUtil {
	
	
	/**   
	 * @Title:      read   
	 * @Description:读取CSV文件   
	 * @param:      @param file
	 * @param:      @return      
	 * @return:     List<CsvRow>      
	 * @throws   
	 */
	public static List<CsvRow> read(InputStream inputStream) {
		
		CsvReader reader = null;
		
		try {
			reader = CsvUtil.getReader();
			//从文件中读取CSV数据
			CsvData data = reader.read(new InputStreamReader(inputStream));
			return data.getRows();
		} catch (Exception e) {
			log.error("{}", e);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				log.error("{}", e);
			}
		}
		
		return Collections.emptyList();
	}
	
	
	/**   
	 * @Title:      write   
	 * @Description:写入文件   
	 * @param:      @param filePath
	 * @param:      @param lines      
	 * @return:     void      
	 * @throws   
	 */
	public static void write(String filePath, List<String[]> lines) {
		
		//指定路径和编码
		CsvWriter writer = CsvUtil.getWriter(filePath, CharsetUtil.CHARSET_UTF_8);
		writer.write(lines);
		writer.flush();
		writer.close();
		
	}
	

}
